import QtQuick 2.0
import "./Custom"

Unit {
    id: player
    width: body.width
    height: body.height

    Component.onCompleted:
    {
        moveSpeed = 10
        _MAX_HEALTHY = healthy = 10
        lifeColor = Qt.rgba(22/255,159/255,27/255,1)
    }

    property bool toRight: false
    property bool toDown: false
    property bool toLeft: false
    property bool toUp: false
    property real gAngle: 0

    property var _ROLES: [
        "qrc:/images/man1.png",
        "qrc:/images/man2.png",
        "qrc:/images/man3.png",
    ]

    function moveToRight(v)
    {
        toRight = v
    }
    function moveToDown(v)
    {
        toDown = v
    }
    function moveToLeft(v)
    {
        toLeft = v
    }
    function moveToUp(v)
    {
        toUp = v
    }
    function setAngle(angle)
    {
        // 角度是反的
        gAngle = angle + 180
//        console.log("gAngle ", angle, gAngle)
    }

    function update()
    {
        if(toRight)
        {
            player.x += moveSpeed
        }
        if(toDown)
        {
            player.y += moveSpeed
        }
        if(toLeft)
        {
            player.x -= moveSpeed
        }
        if(toUp)
        {
            player.y -= moveSpeed
        }

        // 边界检测
        if(player.x <= 0) player.x = 0
        if(player.x >= _WIDTH - player.width) player.x = _WIDTH - player.width
        if(player.y <= 0) player.y = 0
        if(player.y >= _HEIGHT - player.height) player.y = _HEIGHT - player.height
    }

    function setRole(v)
    {
        body.source = _ROLES[v]
    }

    function getSendWeaponPos()
    {
        // 武器的起始位置 是箭头位置
        var pos = Qt.point(0,0)
        var radius = 30
        var radian = gAngle / 180 * Math.PI
        pos.x = player.x + imgHu.x + imgHu.width/2 + radius * Math.cos(radian)
        pos.y = player.y + imgHu.y + imgHu.height/2 + radius * Math.sin(radian)
        return pos
    }

    onDie:
    {
        // die
    }

    onByHit: {
        // 闪
        animFlash.restart()
    }

    Image {
        id: imgShadown
        source: "qrc:/images/shadown.png"
        anchors.horizontalCenter: parent.horizontalCenter
        y: body.y + body.height - height/2
    }
    Image{
        id: body
        source: ""
        width: 20
        fillMode: Image.PreserveAspectFit
    }
    Image{
        id: imgHu
        source: "qrc:/images/hu.png"
        rotation: gAngle
        anchors.centerIn: parent
    }

    SequentialAnimation{
        id: animFlash
        PropertyAnimation{target: body; property: "opacity"; from: 1; to: 0.5; duration: 200; }
        PropertyAnimation{target: body; property: "opacity"; to: 1; duration: 200; }
    }
}
